package cn.topcodes.tcsf.cms.web.controller;

import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.cms.domain.entity.AlbumCatalog;
import cn.topcodes.tcsf.cms.domain.form.AlbumCatalogForm;
import cn.topcodes.tcsf.cms.domain.vo.AlbumCatalogVo;
import cn.topcodes.tcsf.cms.domain.vo.NestableSort;
import cn.topcodes.tcsf.cms.mapper.AlbumCatalogMapper;
import cn.topcodes.tcsf.cms.service.AlbumCatalogService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * AlbumCatalog管理控制器
 *
 * @author Yvan
 * @date 2018-02-09 10:46:26
 */
@Controller
@RequestMapping("/admin/cms/album_catalog")
public class AlbumCatalogController extends AdminController<AlbumCatalog, AlbumCatalogVo, AlbumCatalogForm> {


    @Autowired
    private AlbumCatalogService albumCatalogService;

    @Autowired
    private AlbumCatalogMapper albumCatalogMapper;

    @Override
    protected String getPageFolder() {
        return "/cms/album_catalog";
    }


    @RequestMapping("save-sort")
    @ResponseBody
    public ApiResponseEntity saveSort(@RequestBody(required = true) List<NestableSort> sort) {

        albumCatalogService.saveSort(sort);
        return ApiResponseEntity.buildOK();
    }

    @Override
    public ApiResponseEntity create(HttpServletRequest request,
                                    @Valid @ApiParam("创建资源表单") AlbumCatalogForm form, BindingResult result) {
        ValidationUtil.validate(result);
        Integer maxSort = albumCatalogMapper.findMaxSort();
        AlbumCatalog entity = this.form2Entity(form);
        entity.setSort(maxSort == null ? 0 : ++maxSort);
        Long id = albumCatalogService.create(entity);
        return ApiResponseEntity.buildOK().setBody(id);
    }

    @Override
    public ApiResponseEntity<Void> update(HttpServletRequest request, @Valid @ApiParam("更新资源表单") AlbumCatalogForm form, BindingResult result) {

        AlbumCatalog t = this.form2Entity(form);
        AlbumCatalog articleCatalog = albumCatalogService.findOne(form.getId());
        t.setSort(articleCatalog.getSort());
        albumCatalogService.update(t);
        return ApiResponseEntity.buildOK();
    }
}
